from flask import request, abort, g
from models.store import Store
from models.user import User
from models.user_store import UserStore
from extensions import db
from utils.auth import token_required, generate_token
from flask_restx import Namespace, Resource, fields
import uuid
from datetime import datetime
from sqlalchemy import select, join, or_, desc
from models.card_package import CardPackage

api = Namespace('stores', description='店铺管理相关接口')

# 定义API模型
store_model = api.model('Store', {
    'store_id': fields.String(required=True, description='店铺ID'),
    'name': fields.String(required=True, description='店铺名称'),
    'address': fields.String(required=True, description='店铺地址'),
    'phone': fields.String(required=True, description='联系电话'),
    'description': fields.String(description='店铺描述'),
    'manager_id': fields.String(description='店主ID'),
    'hairdresser_commission_ratio': fields.Float(description='理发师提成比例'),
    'washer_commission_ratio': fields.Float(description='洗头师提成比例'),
    'mentorship_split_ratio': fields.Float(description='师徒分成比例'),
    'created_at': fields.DateTime(description='创建时间'),
    'updated_at': fields.DateTime(description='更新时间'),
    'open_time': fields.String(description='店铺营业开始时间'),
    'close_time': fields.String(description='店铺营业结束时间')
})

store_list_response = api.model('StoreListResponse', {
    'status': fields.String(description='响应状态'),
    'message': fields.String(description='响应消息'),
    'data': fields.List(fields.Nested(store_model))
})

login_model = api.model('StoreLogin', {
    'phone': fields.String(required=True, description='手机号'),
    'password': fields.String(required=True, description='密码')
})

store_response = api.model('StoreResponse', {
    'status': fields.String(description='响应状态'),
    'message': fields.String(description='响应消息'),
    'data': fields.Raw(description='响应数据')
})

user_list_response = api.model('UserListResponse', {
    'status': fields.String(description='响应状态'),
    'message': fields.String(description='响应消息'),
    'data': fields.List(fields.Nested(api.model('UserInfo', {
        'user_id': fields.String(description='用户ID'),
        'username': fields.String(description='用户名'),
        'phone': fields.String(description='手机号'),
        'avatar': fields.String(description='头像URL'),
        'role': fields.String(description='用户角色')
    })))
})

@api.route('', strict_slashes=False)
class StoreList(Resource):
    @api.doc('创建新店铺')
    @api.expect(store_model)
    @api.marshal_with(store_response)
    @token_required
    def post(self):
        """创建新店铺"""
        data = request.get_json()
  
        # 生成店铺ID
        new_store = Store(
            store_id=str(uuid.uuid4()),
            name=data['name'],
            address=data['address'],
            phone=data['phone'],
            manager_id=g.current_identity.user_id,
            open_time=data.get('open_time'),
            close_time=data.get('close_time')
        )
        db.session.add(new_store)
     
        # 创建用户店铺关联关系
        from models.user_store import UserStore
        user_store = UserStore(
            user_id=g.current_identity.user_id,
            store_id=new_store.store_id,
            commission_rate=0.5,# 设置默认佣金比例
            role='owner'  # 设置为店主角色
        )
        db.session.add(user_store)

        # 检查平台股东虚拟用户是否存在，不存在则创建
        platform_shareholder_phone = "8888888888888"  # 13个8
        platform_shareholder = User.query.filter_by(phone=platform_shareholder_phone, is_deleted=False).first()
        
        if not platform_shareholder:
            # 创建平台股东虚拟用户
            platform_shareholder = User(
                user_id=str(uuid.uuid4()),
                name="平台股东",
                phone=platform_shareholder_phone,
                roles="platform_shareholder",
                password=str(uuid.uuid4())  # 生成随机密码
            )
            db.session.add(platform_shareholder)
            db.session.flush()  # 确保获取到用户ID
        
        # 创建平台股东与店铺的关联关系
        platform_user_store = UserStore(
            user_id=platform_shareholder.user_id,
            store_id=new_store.store_id,
            role="platform_shareholder",
            commission_rate=0.0,
            equity_ratio=0.2  # 设置平台股东占股比例，可以根据需求调整
        )
        db.session.add(platform_user_store)

        default_package_list = CardPackage.query.filter_by(
            card_type='default',# 系统默认卡包
            store_id=None,
            user_id=None ,
            is_deleted=False
        ).all()
        for package in default_package_list:
            new_card_package = CardPackage(
                package_id=str(uuid.uuid4()),
                name=package.name,
                card_type=package.card_type,
                store_id=new_store.store_id,  # 关联到新店铺
                parent_card_package_id=package.package_id,  # 设置父卡包ID
                total_amount=package.total_amount,
                remaining_amount=package.remaining_amount,
                discount_rate=package.discount_rate,
                commission_rate=package.commission_rate,
                expiry_date=package.expiry_date,
                recharge_amount=package.recharge_amount,
                gift_amount=package.gift_amount,
                commission_amount=package.commission_amount,
                is_deleted=False
            )
            db.session.add(new_card_package)

        db.session.commit()
        return {
            'status': 'success',
            'message': '店铺创建成功',
            'data': new_store.to_dict()
        }, 200

    @api.doc('获取所有店铺列表', params={'user_id': '用户ID（可选）', 'name': '店铺名称模糊查询（可选）'})
    @api.marshal_with(store_list_response)
    @token_required
    def get(self):
        """获取所有店铺列表"""
        from sqlalchemy import select, join, or_, and_
        
        # 基础查询
        query = select(Store).distinct().join(
            UserStore,
            Store.store_id == UserStore.store_id
        ).where(
            Store.is_deleted == False,
            or_(
                UserStore.role == 'owner',
                and_(
                    Store.manager_id == UserStore.user_id,
                    UserStore.role == 'manager'
                )
            )
        ).order_by(desc(Store.id))

        # 根据角色处理user_id
        if 'admin' not in g.current_identity.roles.split(','):
            user_id = g.current_identity.user_id
            query = query.where(
                or_(
                    UserStore.user_id == user_id,
                    Store.manager_id == user_id
                )
            )
        else:
            user_id = request.args.get('user_id')
            if user_id:
                query = query.where(
                    or_(
                        UserStore.user_id == user_id,
                        Store.manager_id == user_id
                    )
                )
        
        name = request.args.get('name')
        if name:
            query = query.where(Store.name.like(f'%{name}%'))

        stores = db.session.execute(query).scalars().all()
        return {
            'status': 'success',
            'message': '获取成功',
            'data': [store.to_dict() for store in stores]
        }, 200

@api.route('/<store_id>')
class StoreResource(Resource):
    @api.doc('获取单个店铺信息')
    @api.marshal_with(store_response)
    @token_required
    def get(self, store_id):
        """获取单个店铺信息"""
        # 手动实现关联查询
        from sqlalchemy import select, join
        from models.user import User
        store_and_manager = db.session.execute(
            select(Store, User).
            select_from(join(Store, User, Store.manager_id == User.user_id, isouter=True)).
            where(Store.is_deleted == False, Store.store_id == store_id)
        ).first()

        if not store_and_manager:
            abort(404)

        store, manager = store_and_manager
        store_data = store.to_dict()

        if manager:
            store_data['manager'] = manager.to_dict()
        
        return {
            'status': 'success',
            'message': '获取成功',
            'data': store_data
        }, 200

    @api.doc('更新店铺信息')
    @api.expect(store_model)
    @api.marshal_with(store_response)
    @token_required
    def put(self, store_id):
        """更新店铺信息"""
        store = Store.query.filter_by(is_deleted=False, store_id=store_id).first_or_404()
        data = request.get_json()
        
        # 更新店铺信息
        if 'name' in data:
            store.name = data['name']
        if 'address' in data:
            store.address = data['address']
        if 'phone' in data:
            store.phone = data['phone']
        if 'description' in data:
            store.description = data['description']
        
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '店铺信息更新成功',
            'data': store.to_dict()
        }, 200


@api.route('/phone/<phone>')
class StoreByPhone(Resource):
    @api.doc('通过手机号获取店铺信息')
    @api.marshal_with(store_response)
    @token_required
    def get(self, phone):
        """通过手机号获取店铺信息"""
        # 手动实现关联查询
        from sqlalchemy import select, join
        from models.user import User
        store_and_manager = db.session.execute(
            select(Store, User).
            select_from(join(Store, User, Store.manager_id == User.user_id, isouter=True)).
            where(Store.is_deleted == False, Store.phone == phone)
        ).first()

        if not store_and_manager:
            abort(404)

        store, manager = store_and_manager
        store_data = store.to_dict()

        if manager:
            store_data['manager'] = manager.to_dict()

        return {
            'status': 'success',
            'message': '获取成功',
            'data': store_data
        }, 200



    @api.doc('更新店铺信息')
    @api.expect(store_model)
    @api.marshal_with(store_model)
    @token_required
    def put(self, store_id):
        """更新店铺信息"""
        store = Store.query.filter_by(is_deleted=False, store_id=store_id).first_or_404()
        data = request.get_json()
        
        # 更新店铺信息
        if 'name' in data:
            store.name = data['name']
        if 'address' in data:
            store.address = data['address']
        if 'phone' in data:
            store.phone = data['phone']
        if 'description' in data:
            store.description = data['description']
        
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '店铺信息更新成功',
            'data': store.to_dict()
        }, 200

@api.route('/<store_id>/manager')
class StoreManager(Resource):
    @api.doc('更新店铺店主')
    @api.expect(api.model('StoreManager', {
        'manager_id': fields.String(required=True, description='新店主ID')
    }))
    @api.marshal_with(user_list_response)
    @token_required
    def put(self, store_id):
        """更新店铺店主（仅限admin角色）"""
        # 验证当前用户是否为admin
        if 'admin' not in g.current_identity.roles.split(','):
            return {
                'status': 'error',
                'message': '只有管理员可以修改店铺店主',
                'data': None
            }, 403
        
        store = Store.query.filter_by(is_deleted=False, store_id=store_id).first_or_404()
        data = request.get_json()
        
        if 'manager_id' not in data:
            return {
                'status': 'error',
                'message': '缺少必填字段: manager_id',
                'data': None
            }, 400
        
        # 验证新店主是否存在
        manager = User.query.filter_by(user_id=data['manager_id'], is_deleted=False).first()
        if not manager:
            return {
                'status': 'error',
                'message': '指定的店主不存在'
            }, 400
        
        store.manager_id = data['manager_id']
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '店铺店主更新成功',
            'data': store.to_dict()
        }, 200

@api.route('/<store_id>/users')
class StoreUsers(Resource):
    @api.doc('获取店铺下的所有用户', params={
        'page': '页码', 
        'limit': '每页数量', 
        'name': '用户名或手机号模糊查询（可选）',
        'roles[]': '用户角色数组（可选，如：理发师,洗头师）'
    })
    @api.marshal_with(store_response)
    @token_required
    def get(self, store_id):
        """获取店铺下的所有用户"""
        page = request.args.get('page', default=1, type=int)
        limit = request.args.get('limit', default=10, type=int)
        name = request.args.get('name')
        # 获取角色数组，如果roles[]参数不存在则设为None
        roles_param = request.args.get('roles[]')
        roles = roles_param.split(",") if roles_param else None
        
        # 查询店铺下的所有用户关系
        from sqlalchemy import select, join, or_
        user_stores_query = select(UserStore).filter_by(store_id=store_id).order_by(desc(UserStore.id))
        
        # 添加角色过滤条件
        if roles:
            user_stores_query = user_stores_query.filter(UserStore.role.in_(roles))
        
        if name:
            user_stores_query = user_stores_query\
                .select_from(UserStore)\
                .join(User, UserStore.user_id == User.user_id)\
                .filter(
                    or_(
                        User.name.like(f'%{name}%'),
                        User.phone.like(f'%{name}%')
                    )
                )
        else:
            user_stores_query = user_stores_query.select_from(UserStore)
        
        user_stores_pagination = db.paginate(
            user_stores_query,
            page=page,
            per_page=limit,
            error_out=False
        )
        
        # 获取用户详细信息
        result = []
        for user_store in user_stores_pagination.items:
            user = User.query.filter_by(user_id=user_store.user_id, is_deleted=False).first()
            if user:
                user_data = user.to_dict()
                user_data['role'] = user_store.role
                # 添加提成比例和占股比例
                user_data['commission_rate'] = user_store.commission_rate if user_store.commission_rate is not None else 0.0
                user_data['equity_ratio'] = user_store.equity_ratio if user_store.equity_ratio is not None else 0.0
                
                # 特别处理平台股东用户
                if user_store.role == 'platform_shareholder':
                    # 确保平台股东的提成信息正确显示
                    user_data['commission_rate'] = user_store.commission_rate if user_store.commission_rate is not None else 0.0
                    user_data['equity_ratio'] = user_store.equity_ratio if user_store.equity_ratio is not None else 0.2  # 默认占股20%
                
                result.append(user_data)
        
        return {
            'status': 'success',
            'message': '查询店铺用户',
            'data': {
                'list':result, 
                'total': user_stores_pagination.total
            }
        }, 200

@api.route('/<store_id>/users/<user_id>')
class StoreUserBind(Resource):
    @api.doc('绑定用户到店铺')
    @api.marshal_with(user_list_response)
    @token_required
    def post(self, store_id, user_id):
        """绑定用户到店铺"""
        store = Store.query.filter_by(is_deleted=False, store_id=store_id).first_or_404()
        
        # 验证用户是否存在
        user = User.query.filter_by(user_id=user_id, is_deleted=False).first()
        if not user:
            return {
                'status': 'error',
                'message': '用户不存在'
            }, 404
        
        # 检查是否已存在关联
        existing = UserStore.query.filter_by(user_id=user_id, store_id=store_id).first()
        if existing:
            return {
                'status': 'error',
                'message': '该用户已与店铺关联'
            }, 400
        
        # 创建新的用户店铺关系
        user_store = UserStore(
            user_id=user_id,
            store_id=store_id,
            role='staff'  # 默认角色为员工
        )
        
        db.session.add(user_store)
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '用户绑定成功',
            'data': user_store.to_dict()
        }, 200

    @api.doc('删除店铺')
    @api.marshal_with(store_response)
    @token_required
    def delete(self, store_id):
        """删除店铺"""
        store = Store.query.filter_by(is_deleted=False, store_id=store_id).first_or_404()
        
        store.is_deleted = True
        store.deleted_at = datetime.utcnow()
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '店铺删除成功'
        }, 200